<template>
  <div class="proDetail-container">
    <div>
      <el-form
        ref="formRef"
        class="form-container"
        label-position="left"
        label-width="150px"
        :model="detail"
        :rules="rules"
      >
        <!-- <el-form-item label="编号">
          <span>{{ detail.id || 0 }}</span>
        </el-form-item> -->
        <div class="form-item left">
          <el-form-item :label="translate('内部编码') + ' (#pi)'">
            <el-input
              v-model="detail.innerCode"
              prop="innerCode"
              style="width: 350px"
            />
          </el-form-item>
          <el-form-item :label="translate('条形码') + ' (#pc)'" prop="code">
            <el-input v-model="detail.code" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('商品名称') + ' (#pn)'" prop="name">
            <el-input v-model="detail.name" style="width: 350px" />
          </el-form-item>
          <el-form-item
            :label="translate('商品类别') + ' (#ps)'"
            prop="CategoryId"
          >
            <el-input
              v-model="detail.CategoryId"
              maxlength="6"
              style="width: 350px"
            />
          </el-form-item>
          <el-form-item :label="translate('规格') + ' (#ps)'" prop="spec">
            <el-input v-model="detail.spec" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('级别') + ' (#pg)'" prop="grade">
            <el-input v-model="detail.grade" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('单位') + ' (#pu)'" prop="unit">
            <el-input v-model="detail.unit" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('价格') + ' (#pp)'" prop="price">
            <el-input-number
              v-model="detail.price"
              :precision="2"
              :step="0.1"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item :label="translate('会员价') + ' (#vp)'" prop="vipPrice">
            <el-input-number
              v-model="detail.vipPrice"
              :precision="2"
              :step="0.1"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item
            :label="translate('原价') + ' (#pop)'"
            prop="originPrice"
          >
            <el-input-number
              v-model="detail.originPrice"
              :precision="2"
              :step="0.1"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item :label="translate('产地') + ' (#po)'">
            <el-input v-model="detail.origin" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('售货员') + ' (#pm)'">
            <el-input v-model="detail.vendeur" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('促销类型')">
            <el-select
              v-model="detail.promotion"
              :placeholder="translate('请选择')"
            >
              <el-option
                v-for="item in promotionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="form-item right">
          <el-form-item :label="translate('自定义1') + ' (#f1)'">
            <el-input v-model="detail.field1" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('自定义2') + ' (#f2)'">
            <el-input v-model="detail.field2" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('自定义3') + ' (#f3)'">
            <el-input v-model="detail.field3" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('二维码地址') + ' (#f4)'">
            <el-input v-model="detail.field4" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('型号图片地址') + ' (#f5)'">
            <el-input v-model="detail.field5" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('自定义6') + ' (#f6)'">
            <el-input v-model="detail.field6" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('库存') + ' (#kc)'">
            <el-input-number
              v-model="detail.storage"
              :min="0"
              :precision="0"
              :step="1"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item :label="translate('库存阈值')">
            <el-input-number
              v-model="detail.storageThreshold"
              :min="0"
              :precision="0"
              :step="1"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item :label="translate('状态')">
            <el-switch
              v-model="detail.status"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <!-- <el-form-item label="是否同步">
            <el-switch
              v-model="detail.isSync"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item> -->
          <el-form-item :label="translate('图片')">
            <el-upload
              v-model:file-list="fileList"
              :accept="accept"
              :action="action"
              :before-upload="beforeAvatarUpload"
              class="avatar-uploader"
              :headers="headers"
              list-type="picture-card"
              multiple
              name="fileInput"
              :on-success="handleAvatarSuccess"
              :show-file-list="true"
            >
              <!-- <div
                v-if="imageUrl"
                class="avatar-container"
                :style="{
                  width: width,
                  height: height,
                }"
              >
                <el-image class="avatar" fit="contain" :src="imageUrl" />
              </div> -->
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <!-- <ImgUpload
              :filelist="detail.uniqueCode"
              :image-url="detail.customImage"
              @success="uploadSuccess"
            /> -->
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div>
      <el-form
        ref="formRef"
        class="form-container bottom"
        label-position="left"
        label-width="120px"
        :model="detail"
      >
        <div class="form-item1">
          <el-form-item label="商品详情：" label-width="120">
            <div class="richText">
              <richText
                :content="detail.proIntroduce"
                @richText="richTextChange"
              />
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="btns">
      <ElButton class="btn mr20" type="primary" @click="save">
        {{ translate('保存') }}
      </ElButton>
      <ElButton class="btn" @click="cancel">{{ translate('取消') }}</ElButton>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { getpro, proedit } from '@/api/mupro'
  import router from '@/router'
  import ImgUpload from '@/views/components/imgUpload/index.vue'
  import { translate } from '@/i18n'
  import richText from '../components/richText.vue'
  import { useUserStore } from '@/store/modules/user'
  import { baseURL } from '@/config'
  const { token } = useUserStore()
  const headers = reactive({ Authorization: `Bearer ${token}` })
  const rules = reactive({
    innerCode: [
      {
        required: true,
        message: translate('请填写条形码'),
        trigger: 'blur',
      },
    ],
    name: [
      {
        required: true,
        message: translate('请填写商品名称'),
        trigger: 'blur',
      },
    ],
    unit: [
      {
        required: true,
        message: translate('请填写商品单位'),
        trigger: 'blur',
      },
    ],
    price: [
      {
        required: true,
        message: translate('请填写商品价格'),
        trigger: 'blur',
      },
    ],
    vipPrice: [
      {
        required: true,
        message: translate('请填写商品会员价'),
        trigger: 'blur',
      },
    ],
    originPrice: [
      {
        required: true,
        message: translate('请填写商品原价'),
        trigger: 'blur',
      },
    ],
  })
  const promotionList = ref([
    {
      label: 'Normal',
      value: '1',
    },
    {
      label: 'VIP',
      value: '2',
    },
    {
      label: 'Promotion',
      value: '3',
    },
    {
      label: 'Limit',
      value: '4',
    },
  ])
  const action = ref(`${baseURL}` + '/WF_Document/UploadFile')
  const accept = ref('image/jpg, image/jpeg,image/png')
  const fileList = ref([])
  const route = useRoute()
  const id: any = ref('0')
  const content: any = ref('')
  const init = async () => {
    if (route.query && route.query.ID) {
      id.value = route.query.ID
    }
  }
  const detail: any = ref({})
  const getDetail = async () => {
    const {
      data: { data },
      code,
    } = await getpro({
      id: id.value,
    })

    detail.value = data
    content.value = detail.value.proIntroduce ? detail.value.proIntroduce : ''
    if (detail.value.uniqueCode) {
      detail.value.uniqueCode = JSON.parse(detail.value.uniqueCode)
    } else {
      detail.value.uniqueCode = [
        {
          url: detail.value.customImage,
        },
      ]
    }
    fileList.value = detail.value.uniqueCode
    console.log(detail.value.uniqueCode)
  }
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // if (rawFile.type !== 'image/jpeg') {
    //   ElMessage.error('Avatar picture must be JPG format!')
    //   return false
    // } else if (rawFile.size / 1024 / 1024 > 2) {
    //   ElMessage.error('Avatar picture size can not exceed 2MB!')
    //   return false
    // }
    if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('Avatar picture size can not exceed 2MB!')
      return false
    }
    return true
  }
  const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
  ) => {
    if (response.code == 200) {
      console.log(response)
      // emit('success', URL.createObjectURL(uploadFile.raw!))
      uploadSuccess(fileList.value)
      // emit('success', fileList.value)
    }
    // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  }

  init().then(() => {
    if (id.value && id.value !== '0') {
      getDetail()
    }
  })
  const uploadSuccess = (url: any) => {
    console.log(url)
    const pic = []
    if (url) {
      url.map((item) => {
        if (!item.response) {
          pic.push({
            url: item.url,
          })
        } else {
          pic.push({ url: item.response.data })
        }
      })
    }
    console.log(pic)
    console.log(fileList.value)
    detail.value.customImage = pic ? pic[0].url : ''
    detail.value.uniqueCode = JSON.stringify(pic)
  }
  const richTextChange = (val: any) => {
    content.value = val
    console.log(val)
  }
  const formRef: any = ref(null)
  const save = async () => {
    await formRef.value.validate(async (valid: any) => {
      if (valid) {
        console.log(valid)
        console.log(detail.value)
        if (typeof detail.value.uniqueCode !== 'string') {
          detail.value.uniqueCode = JSON.stringify(detail.value.uniqueCode)
        }
        detail.value.ProIntroduce = content.value
        const { code } = await proedit(detail.value)
        if (code == 200) {
          router.back()
        }
      }
    })
  }
  const cancel = () => {
    router.back()
  }
</script>

<style lang="scss" scoped>
  .proDetail-container {
    .form-container {
      display: flex;
      justify-content: space-around;

      .form-item {
        width: 40%;
        padding: 14px 20px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.12);
      }
      .form-item1 {
        width: 60%;
        padding: 14px 20px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.12);
      }
    }
    .buttom {
      justify-content: space-around !important;
    }
    .btns {
      display: flex;
      justify-content: center;
      margin-top: 30px;

      .mr20 {
        margin-right: 10px;
      }
    }
  }
</style>
